package com.avic.modules.record.service.impl;

import com.avic.common.service.impl.BaseServiceImpl;
import com.avic.common.utils.QueryHelpPlus;
import com.avic.modules.equipment.cache.CacheService;
import com.avic.modules.equipment.domain.Equipment;
import com.avic.modules.equipment.service.EquipmentService;
import com.avic.modules.equipment.service.dto.EquipmentQueryCriteria;
import com.avic.modules.equipment.service.mapper.EquipmentMapper;
import com.avic.modules.mapping.domain.DataMapping;
import com.avic.modules.mapping.service.DataMappingService;
import com.avic.modules.mapping.service.dto.DataMappingQueryCriteria;
import com.avic.modules.record.domain.SeeYouTomorrow;
import com.avic.modules.record.domain.Yesterday;
import com.avic.modules.record.service.YesterdayService;
import com.avic.modules.record.service.dto.YesterdayQueryCriteria;
import com.avic.modules.record.service.mapper.SeeYouTomorrowMapper;
import com.avic.modules.record.service.mapper.YesterdayMapper;
import com.avic.modules.statistics.domain.KanbanStatistics;
import com.avic.modules.statistics.domain.MonthlyStatistics;
import com.avic.modules.statistics.domain.MonthlyStatusRecord;
import com.avic.modules.statistics.service.KanbanStatisticsService;
import com.avic.modules.statistics.service.MonthlyStatisticsService;
import com.avic.modules.statistics.service.MonthlyStatusRecordService;
import com.avic.utils.RedisUtils;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhangzikang 昨日记录表
 * @date 2022-08-14
 */
@Service(value = "yesterdayService")
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YesterdayServiceImpl extends BaseServiceImpl
        <YesterdayMapper, Yesterday> implements YesterdayService {

    private final YesterdayMapper yesterdayMapper;
    private final EquipmentService equipmentService;
    private final DataMappingService dataMappingService;
    private final SeeYouTomorrowMapper seeYouTomorrowMapper;
    private final KanbanStatisticsService kanbanStatisticsService;
    private final CacheService cacheService;
    private final EquipmentMapper equipmentMapper;
    private final RedisUtils redisUtils;
    private final MonthlyStatisticsService monthlyStatisticsService;
    private final MonthlyStatusRecordService monthlyStatusRecordService;

    /**
     * 查询某个类别下的昨日记录
     * @param yesterday
     * @return
     */
    @Override
    public List<Yesterday> selectCategoryId(YesterdayQueryCriteria yesterday) {
        return baseMapper.selectList(QueryHelpPlus.getPredicate(Yesterday.class,yesterday));
    }

    /**
     * 修改昨日记录
     */
    @Override
    @Scheduled(cron = "10 59 23 * * ?")
    public void updateYesterday() {
        try {
            yesterdayMapper.del();
            cacheService.deleteRunningKeys(equipmentMapper,redisUtils);
            EquipmentQueryCriteria criteria = new EquipmentQueryCriteria();
            List<Equipment> equipment = equipmentService.queryAll(criteria);
            Calendar cal = Calendar.getInstance();
            Date date=new Date(); //现在的日期
            cal.setTime(date);
            for(Equipment equip:equipment){
                if(equip.getEquipCategoryId()>4 && equip.getDeviceType()==2){
                    if(equip.getEquipCategoryId()==7){
                        modifySeeYouTomorrow(equip.getId());
                    }
                    Yesterday yesterday = new Yesterday();
                    yesterday.setCategory(equip.getEquipCategoryId());
                    yesterday.setStation(equip.getStackNumber());
                    yesterday.setEquipId(equip.getId());
                    yesterday.setFunctionType(equip.getRunningState());
                    yesterday.setHealthyType(equip.getHealthStatus());
                    String replace = UUID.randomUUID().toString().replace("-", "");
                    yesterday.setId(replace);
                    yesterdayMapper.insert(yesterday);
                }
                KanbanStatistics kanbanStatistics = kanbanStatisticsService.queryKanbanStatistics(equip.getId());
                if(kanbanStatistics!=null){

                    MonthlyStatistics monthlyStatistics = monthlyStatisticsService.queryMonthlyStatistics(equip.getId());
                    long shutdownTime = kanbanStatistics.getShutdownTime();
                    long runningTime = kanbanStatistics.getRunningTime();
                    long total = shutdownTime + runningTime;
                    if(monthlyStatistics!=null){

                        Integer day = cal.get(Calendar.DAY_OF_MONTH) - 1;
                        long montCount = day * 86400;


                        int operation = monthlyStatistics.getMonthlyOperation() + kanbanStatistics.getRunningQuantity();
                        int shutdown = monthlyStatistics.getMonthlyShutdown() + kanbanStatistics.getShutdownQuantity();
                        long monthlyOperationTime = monthlyStatistics.getMonthlyOperationTime();
                        long monthlyShutdownTime = monthlyStatistics.getMonthlyShutdownTime();
                        long montTotal = monthlyOperationTime + monthlyShutdownTime + total;

                        if(montCount > montTotal){
                            long ontSum = montCount - montTotal;
                            monthlyStatistics.setMonthlyShutdown(shutdown +1);
                            monthlyStatistics.setMonthlyShutdownTime(monthlyShutdownTime + shutdownTime + ontSum);
                        } else {
                            monthlyStatistics.setMonthlyShutdown(shutdown);
                            monthlyStatistics.setMonthlyShutdownTime(monthlyShutdownTime + shutdownTime);
                        }
                        monthlyStatistics.setMonthlyOperation(operation);
                        monthlyStatistics.setMonthlyOperationTime(monthlyOperationTime + runningTime);
                        monthlyStatisticsService.eatMonthlyStatistics(monthlyStatistics);
                    }else {
                        MonthlyStatistics statistics = new MonthlyStatistics();
                        long number = 86400;
                        if(number > total) {
                            long montCount = number - total;
                            statistics.setMonthlyShutdown(kanbanStatistics.getShutdownQuantity() + 1);
                            statistics.setMonthlyShutdownTime(shutdownTime + montCount);
                        }else {
                            statistics.setMonthlyShutdown(kanbanStatistics.getShutdownQuantity());
                            statistics.setMonthlyShutdownTime(shutdownTime);
                        }

                        statistics.setEquipId(equip.getId());
                        statistics.setMonthlyOperation(kanbanStatistics.getRunningQuantity());
                        statistics.setMonthlyOperationTime(runningTime);
                        monthlyStatisticsService.addMonthlyStatistics(statistics);
                    }
                    kanbanStatistics.setShutdownQuantity(0);
                    kanbanStatistics.setRunningQuantity(0);
                    kanbanStatistics.setShutdownTime(0L);
                    kanbanStatistics.setRunningTime(0L);
                    kanbanStatistics.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    kanbanStatisticsService.eatKanbanStatistics(kanbanStatistics);
                } else {
                    KanbanStatistics statistics = new KanbanStatistics();
                    statistics.setEquipId(equip.getId());
                    statistics.setCreateTime(new Timestamp(System.currentTimeMillis()));
                    kanbanStatisticsService.addKanbanStatistics(statistics);
                    MonthlyStatistics monthlyStatistics1 = new MonthlyStatistics();
                    monthlyStatistics1.setEquipId(equip.getId());
                    monthlyStatisticsService.addMonthlyStatistics(monthlyStatistics1);
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加设备看板信息
     */
    @Override
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void addMonthlyStatusRecord() {
        DataMappingQueryCriteria criteria = new DataMappingQueryCriteria();
        criteria.setRecordCate(22L);
        criteria.setRecordType(5);
        List<DataMapping> dataMappings = dataMappingService.selectRunningDataMapping(criteria);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        for(DataMapping map:dataMappings){
            Equipment equipment = equipmentMapper.selectById(map.getEquipId());
            List<MonthlyStatusRecord> monthlyStatusRecords = monthlyStatusRecordService.queryMonthlyStatusRecordTotal(map.getEquipId(),format);
            // 每天只产生30条
            if(equipment!=null && monthlyStatusRecords.size() < 30){
                MonthlyStatusRecord monthlyStatusRecord = new MonthlyStatusRecord();
                monthlyStatusRecord.setEquipId(equipment.getId());
                monthlyStatusRecord.setCreationDate(format);
                monthlyStatusRecord.setStatus(Integer.parseInt(map.getValue()));
                monthlyStatusRecordService.insert(monthlyStatusRecord);
            }
        }

    }

    // 修改昨日污染度
    public void modifySeeYouTomorrow(String equipId){
        Equipment equip = equipmentMapper.selectById(equipId);
        SeeYouTomorrow seeYouTomorrow = new SeeYouTomorrow();
        seeYouTomorrow.setEquipId(equip.getId());
        List<DataMapping> dataMappings = dataMappingService.selectEquipMapping(equip.getId(),equip.getEquipCategoryId());
        for(DataMapping data:dataMappings){
            if(data.getRecordCate()==12){
                seeYouTomorrow.setHeatTransfer(data.getValue());
            } else if(data.getRecordCate()==13){
                seeYouTomorrow.setOilSource(data.getValue());
            }
        }

        if(dataMappings.size()>0){
            SeeYouTomorrow seeYouTomorrow1 = seeYouTomorrowMapper.selectEquipId(equip.getId());
            if(seeYouTomorrow1 == null){
                seeYouTomorrowMapper.insert(seeYouTomorrow);
            } else {
                seeYouTomorrow.setId(seeYouTomorrow1.getId());
                seeYouTomorrowMapper.updateById(seeYouTomorrow);
            }
        }
    }
}
